document.addEventListener('DOMContentLoaded', () => {
  const svgNS = 'http://www.w3.org/2000/svg';
  const canvas = document.getElementById('canvas');
  const addNodeButton = document.getElementById('addNode');
  
  let nodes = [];
  let links = [];
  
  addNodeButton.addEventListener('click', addNode);

  function addNode() {
    const newNode = createNode();
    canvas.appendChild(newNode);
    nodes.push(newNode);
    makeDraggable(newNode);
  }

  function createNode() {
    const group = document.createElementNS(svgNS, 'g');
    const rect = document.createElementNS(svgNS, 'rect');
    rect.setAttribute('x', 50);
    rect.setAttribute('y', 50);
    rect.setAttribute('width', 100);
    rect.setAttribute('height', 50);
    rect.setAttribute('fill', '#007BFF');
    rect.setAttribute('stroke', '#000');
    
    const connectors = ['top', 'bottom', 'left', 'right'].map(position => createConnector(position));

    connectors.forEach(connector => group.appendChild(connector));
    group.appendChild(rect);
    group.classList.add('node');
    group.setAttribute('transform', 'translate(0, 0)');
    group.setAttribute('data-id', `node-${nodes.length + 1}`);

    return group;
  }

  function createConnector(position) {
    const circle = document.createElementNS(svgNS, 'circle');
    circle.setAttribute('r', 5);
    circle.setAttribute('fill', '#FF0');
    circle.setAttribute('stroke', '#000');  // 设置边框颜色为黑色
    circle.setAttribute('stroke-width', 1); // 设置边框宽度
    circle.classList.add('connector');
    circle.dataset.position = position;

    switch (position) {
      case 'top':
        circle.setAttribute('cx', 100);
        circle.setAttribute('cy', 45);
        break;
      case 'bottom':
        circle.setAttribute('cx', 100);
        circle.setAttribute('cy', 105);
        break;
      case 'left':
        circle.setAttribute('cx', 45);
        circle.setAttribute('cy', 75);
        break;
      case 'right':
        circle.setAttribute('cx', 155);
        circle.setAttribute('cy', 75);
        break;
    }
    
    return circle;
  }

  function makeDraggable(node) {
    let offsetX, offsetY;
    const rect = node.querySelector('rect');
    
    rect.addEventListener('mousedown', (e) => {
      const nodeRect = rect.getBoundingClientRect();
      offsetX = e.clientX - nodeRect.x;
      offsetY = e.clientY - nodeRect.y;
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    });

    function onMouseMove(e) {
      const newX = e.clientX - offsetX-45;
      const newY = e.clientY - offsetY-100;

      if (!isNaN(newX) && !isNaN(newY)) {
        node.setAttribute('transform', `translate(${newX}, ${newY})`);
        updateLinks();
      }
    }

    function onMouseUp() {
      document.removeEventListener('mousemove', onMouseMove);
      document.removeEventListener('mouseup', onMouseUp);
    }
  }

  let startConnector = null;

  canvas.addEventListener('click', (e) => {
    if (e.target.classList.contains('connector')) {
      if (startConnector) {
        const endConnector = e.target;
        if (startConnector !== endConnector) {
          createLink(startConnector, endConnector);
          startConnector = null;
        }
      } else {
        startConnector = e.target;
      }
    }
    if (e.target.tagName === 'path') {
      selectLink(e.target);
    }
  });
  canvas.addEventListener('contextmenu', (e) => {
    e.preventDefault();
    if (e.target.tagName === 'path') {
      deleteLink(e.target);
    }
  });
  function createLineLink(startConnector, endConnector) {
    const startCoords = getConnectorCoords(startConnector);
    const endCoords = getConnectorCoords(endConnector);

    const line = document.createElementNS(svgNS, 'line');
    line.setAttribute('x1', startCoords.x);
    line.setAttribute('y1', startCoords.y);
    line.setAttribute('x2', endCoords.x);
    line.setAttribute('y2', endCoords.y);
    line.setAttribute('stroke', '#000');
    line.dataset.startNodeId = startConnector.parentElement.dataset.id;
    line.dataset.startPosition = startConnector.dataset.position;
    line.dataset.endNodeId = endConnector.parentElement.dataset.id;
    line.dataset.endPosition = endConnector.dataset.position;
    canvas.appendChild(line);
    links.push(line);
  }

  function createLink(startConnector, endConnector) {
    const path = document.createElementNS(svgNS, 'path');
    path.setAttribute('stroke', '#000');
    path.setAttribute('fill', 'none');
    path.dataset.startNodeId = startConnector.parentElement.dataset.id;
    path.dataset.startPosition = startConnector.dataset.position;
    path.dataset.endNodeId = endConnector.parentElement.dataset.id;
    path.dataset.endPosition = endConnector.dataset.position;
    canvas.appendChild(path);
    links.push(path);
    updateLinks();
  }

  function getConnectorCoords(connector) {
    const transform = connector.parentElement.getAttribute('transform');
    const translate = transform.match(/translate\(([^,]+),\s*([^\)]+)\)/);
    if (translate) {
      const parentX = parseFloat(translate[1]);
      const parentY = parseFloat(translate[2]);
      const cx = parseFloat(connector.getAttribute('cx'));
      const cy = parseFloat(connector.getAttribute('cy'));
      return { x: parentX + cx, y: parentY + cy };
    }
    return { x: 0, y: 0 };
  }

  function updateLineLinks() {
    links.forEach(link => {
      const startNode = document.querySelector(`[data-id="${link.dataset.startNodeId}"]`);
      const endNode = document.querySelector(`[data-id="${link.dataset.endNodeId}"]`);
      const startConnector = startNode.querySelector(`.connector[data-position="${link.dataset.startPosition}"]`);
      const endConnector = endNode.querySelector(`.connector[data-position="${link.dataset.endPosition}"]`);
      const startCoords = getConnectorCoords(startConnector);
      const endCoords = getConnectorCoords(endConnector);
      link.setAttribute('x1', startCoords.x);
      link.setAttribute('y1', startCoords.y);
      link.setAttribute('x2', endCoords.x);
      link.setAttribute('y2', endCoords.y);
    });
  }
  function updateLinks() {
    links.forEach(link => {
      const startNode = document.querySelector(`[data-id="${link.dataset.startNodeId}"]`);
      const endNode = document.querySelector(`[data-id="${link.dataset.endNodeId}"]`);
      const startConnector = startNode.querySelector(`.connector[data-position="${link.dataset.startPosition}"]`);
      const endConnector = endNode.querySelector(`.connector[data-position="${link.dataset.endPosition}"]`);
      const startCoords = getConnectorCoords(startConnector);
      const endCoords = getConnectorCoords(endConnector);

      // 使用 getAvoidingPath 函数计算避开节点的路径
      const pathData = getAvoidingPath(startCoords, endCoords);
      link.setAttribute('d', pathData);
    });
  }

  function getAvoidingPath(start, end) {
    // 确定起点和终点的中间点
    const midX = (start.x + end.x) / 2;
    const midY = (start.y + end.y) / 2;

    // 设置初始路径
    let path = `M ${start.x} ${start.y}`;

    // 水平或垂直连接器情况处理
    if (Math.abs(start.x - end.x) > Math.abs(start.y - end.y)) {
      path += ` L ${midX} ${start.y} L ${midX} ${end.y} L ${end.x} ${end.y}`;
    } else {
      path += ` L ${start.x} ${midY} L ${end.x} ${midY} L ${end.x} ${end.y}`;
    }

    // 额外处理路径避免节点
    nodes.forEach(node => {
      const rect = node.querySelector('rect');
      const rectTransform = node.getAttribute('transform');
      const rectTranslate = rectTransform.match(/translate\(([^,]+),\s*([^\)]+)\)/);
      const rectX = parseFloat(rectTranslate[1]) + parseFloat(rect.getAttribute('x'));
      const rectY = parseFloat(rectTranslate[2]) + parseFloat(rect.getAttribute('y'));
      const rectWidth = parseFloat(rect.getAttribute('width'));
      const rectHeight = parseFloat(rect.getAttribute('height'));

      if (isIntersectingPath(rectX, rectY, rectWidth, rectHeight, start, end)) {
        // 计算新的避开路径点
        if (start.x < end.x) {
          path = `M ${start.x} ${start.y} L ${start.x} ${rectY - 10} L ${end.x} ${rectY - 10} L ${end.x} ${end.y}`;
        } else {
          path = `M ${start.x} ${start.y} L ${start.x} ${rectY + rectHeight + 10} L ${end.x} ${rectY + rectHeight + 10} L ${end.x} ${end.y}`;
        }
      }
    });

    return path;
  }

  function isIntersectingPath(rectX, rectY, rectWidth, rectHeight, start, end) {
    const buffer = 10; // 路径缓冲区
    return !(end.x < rectX - buffer ||
             start.x > rectX + rectWidth + buffer ||
             end.y < rectY - buffer ||
             start.y > rectY + rectHeight + buffer);
  }

  function selectLink(link) {
    if (selectedLink) {
      selectedLink.classList.remove('selected');
    }
    selectedLink = link;
    selectedLink.classList.add('selected');
  }

  function deleteLink(link) {
    canvas.removeChild(link);
    const index = links.indexOf(link);
    if (index !== -1) {
      links.splice(index, 1);
    }
    selectedLink = null;
  }
});
